#include "AptList.h"


AptList::AptList() {
  index = new apt::Apt::Iterator(myapt.begin());
  packpath="/var/lib/dpkg/info";
  if (packpath[packpath.size()]!='/') packpath.append("/");
  ind=1;
  conf.delay=5;
}

Pkg AptList::GetAPkg() {

  Pkg currp;
  size_t i;
  stringstream sstat;
      
  if (*index != myapt.end()) {
    PackageRecord record(myapt.rawRecord(**index));
    

    PackageState state = myapt.state(**index);

    currp.SetField("Short-Description",record.shortDescription());

    if (state.isInstalled()) {
      for(i=0;i<record.size();i++) {
	currp.SetField(record.name(i),record.lookup(i));
      }
    
      i=FillFlist(&currp);
      if(i>0) {
	currp.enabled=true; 

	status.lev=1;
	//status.msg="Package " + currp.GetField("Package") + " loaded, version: " + currp.GetField("Version") + ".";
	sstat << "[#" << ind << "] Package " << currp.GetField("Package") << " loaded.";
	status.msg=sstat.str();
      }
      else {
	status.lev=2;
	sstat << "[#" << ind << "] Package " << currp.GetField("Package") << " loaded with no files.";
	status.msg=sstat.str();

      }
      ind++;
    }
    ++*index;
  }

  else { //in qsto caso dovrebbe stampare il field dell'ultimo pacchetto caricato.. non sembra lo faccia
      status.lev=-1;
      sstat << "[#" << ind << "] Last package " << currp.GetField("Package") << " loaded.";
      status.msg=sstat.str();
  }
  return currp;

}


int AptList::FillFlist(Pkg *pk) {

  string filename= packpath + pk->GetField("Package") + ".list";

  //controllo sull'open
  ifstream infile(filename.c_str()); 

  string str;
  char ret;
  int i=0;

  while( getline( infile, str ) )
  {
	  ret=checkFile(str.c_str());
	  pk->SetFile(str,ret);
	  i++;
  }
  infile.close();
  return i;

}

bool AptList::isInstalled(string str) {

  PackageState state = myapt.state(str.c_str());
  return state.isInstalled();

}